#include "global.h"

void LockSemaphore(Semaphore* s)
{
	mem_lock(); // Disable interrupts
	
	--s->value;
	while(s->value < 0)
	{
		running->status = BLOCK;
		
		if (s->queue == 0)
		{
			s->queue = running;
		}
		else
		{
			Process* p = s->queue;
			while (p->next != 0) { p = p->next; }
			p->next = running;
		}
		
		tswitch();
	}
	
	restore(); // Renable interrupts
}

void UnlockSemaphore(Semaphore* s)
{
	mem_lock(); // Disable interrupts
	
	++s->value;
	while (s->value <= 0)
	{
		Process* p = s->queue;
		s->queue = p->next;
		p->status = READY;
		enqueue(p, &readyQueue);
	}
	
	restore(); // Renable interrupts
}
